<?php

namespace App\Services;

use App\Models\OperationLogModel;
use App\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageModel;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class CommonService
{
    /**
     *
     * Author: Sw
     * Created at 2023/2/27 11:18
     * @param $userId   操作人id
     * @param $time 入口日志生成时间
     * @param $result 请求结果
     * @return int
     */
    public static function operateResult($userId, $time, $result,$logData = "")
    {
        return OperationLogModel::query()->where([
            'user_id' => $userId,
            'created_at' => $time,
        ])
            ->update([
                'request_result' => json_encode($result),
                'log_data'=>$logData,
            ]);
    }

    /**
     * 设置库存预警标记
     * @param $mainId
     * @return true
     */
    public static function setAlertFlag($mainId)
    {
        StorageManageModel::query()->where('main_id', $mainId)
            ->where('alert_num', '!=', 0)
            ->whereRaw('in_storage_num <= alert_num')
            ->update(['sort_flag' => 1]);

        return true;
    }

    public static function cancelAlertFlag($mainId)
    {
        StorageManageModel::query()->where('main_id', $mainId)
            /*->whereRaw('in_storage_num > alert_num')*/
            ->whereColumn('in_storage_num', '>', 'alert_num')
            ->update(['sort_flag' => 0]);

        return true;
    }

    /**
     * 操作日志
     * change 在 2021/10/15 13:32 创建
     * @param $remark 操作描述
     * @param $data   操作详细内容
     */
    public static function log($remark,$data,$logData = ""){
        $res = OperationLogModel::insert([
            'main_id'=>$data['main_id']??0,
            'user_id'=>$data['user_id']??0,
            'remark'=>$remark,
            'data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
            'ip'=>$_SERVER["REMOTE_ADDR"],
            'log_data'=>$logData,
            'created_at'=>$data['time']??time()
        ]);
    }

    /**
     * 成功响应
     * change 在 2024/1/12 10:29 创建
     * @param string $data  响应数据
     * @param string $msg   响应提示
     * @return \Illuminate\Http\JsonResponse
     */
    public static function success($msg='success', $data='', $code=0){

        return response()->json([
            'msg' => $msg,
            'data' => $data,
            'code' => $code,
        ]);
    }
    /**
     * 失败响应
     * change 在 2024/1/12 10:29 创建
     * @param string $data  响应数据
     * @param string $msg   响应提示
     * @return \Illuminate\Http\JsonResponse
     */
    public static function fail($msg='fail', $data='', $code=1){
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
        ]);
    }

    /**
     * 打印sql 语句，开启标记
     * @return void
     */
    public static function getLastSqlStart()
    {
        DB::connection()->enableQueryLog();
    }

    /**
     * 打印sql 语句，结束标记
     * @return void
     */
    public static function getLastSqlEnd()
    {
        $queryLog = DB::getQueryLog();
        // 4. 打印执行的 SQL 语句
        if(!empty($queryLog)){
            foreach ($queryLog as $qSql) {
                $sql = str_replace('?', '%s', $qSql['query']);
                $bindings = array_map(function ($binding) {
                    return is_numeric($binding) ? $binding : "'{$binding}'";
                }, $qSql['bindings']);
                $fullSql = vsprintf($sql, $bindings);
                echo $fullSql;
                echo "\n";
                exit;
            }
        }else{
            exit('没有获取sql语句，请检查是否开启 getLastSqlStart() 函数。');
        }

    }

    /**
     *生成订单号-公共方法
     * Author: zlf
     * Created at 2024/3/21 14:29
     * @param $prefix
     * @param $model
     * @return string
     */
    public static function getOrderNo($model, $param ='', $prefix = ''){
        $year = substr(Carbon::parse()->year, -2);
        $orderNo = $prefix.$year.Carbon::parse()->format('md').mt_rand(100000, 999999);
        do{
            $orderNo = $prefix.$year.Carbon::parse()->format('md').mt_rand(100000, 999999);
        } while(!empty($model::query()->where($param,$orderNo)->exists()));
        return $orderNo;
    }

    /**
     *查看员工和负责相关的仓库列表
     * Author: zlf
     * Created at 2024/3/25 10:26
     * @param $userInfo
     * @return array
     */
    public static function getMultiUser($userInfo):array
    {
        $StorageList = StorageModel::query()->select(
            'id',
            'user_id',
            'multi_user_id'
            )
            ->where([
                'delete_flag' => 0,
                'main_id' => $userInfo['main_id']
            ])->where(function($query)use($userInfo){
                $query->orWhere([
                    ['multi_user_id','!=',''],
                    'user_id' => $userInfo['user_id']
                ]);
            })->get();
        $storageIdArr = [];
        if(!empty($StorageList)){
            foreach ($StorageList->toArray() as $sVal){
                if(!empty($sVal['multi_user_id'])){
                    $multiUserId = array_filter(
                        explode(',',$sVal['multi_user_id']),
                        function($v) {
                            return $v !== '';
                        });
                    if(is_array($multiUserId)){
                        if(in_array($userInfo['user_id'],$multiUserId)){
                            $storageIdArr[] = $sVal['id'];
                        }elseif($sVal['user_id'] == $userInfo['user_id']){
                            $storageIdArr[] = $sVal['id'];
                        }
                    }
                }else{
                    $storageIdArr[] = $sVal['id'];
                }
            }
        }
        return $storageIdArr;
    }
}
